function isImg(uri) {
  return uri.match(/\.(jpeg|jpg|gif|png)$/) != null;
}

async function readEmbedFileContent(params, embed, parentFilePath) {
  let filePath = embed.link;
  filePath = parentFilePath + "/" + filePath;
  let normalizeFilePath = params.app.vault.adapter.path.posix.normalize(filePath);
  let file = params.app.vault.fileMap[normalizeFilePath];
  if (!file) {
    new Notice(`Could not find file ${filePath}`);
    console.error(`Could not find file ${filePath}`);
    return;
  }
  let mdEmbeds = getEmbedList(params, file);
  if (mdEmbeds.length == 0) {
    let fileContent = await params.app.vault.readRaw(filePath);
    return fileContent;
  } else {
    let fileContentArray = [];
    let positionStartOffset = 0;
    var len = mdEmbeds.length;
    console.log("normalizeFilePath = " + normalizeFilePath);
    console.log("引用块数量：" + len);
    let unsafeCachedData = file.unsafeCachedData;
    let currentParentFilePath = file.parent.path;
    for (var i = 0; i < len; i++) {
      let embed = mdEmbeds[i];
      let position = getEmbedPosition(embed);
      let positionEndOffset = position.startOffset;
      let data = unsafeCachedData.substring(positionStartOffset, positionEndOffset);
      fileContentArray.push(data);
      positionStartOffset = position.endOffset;
      if (embed.link.endsWith(".md")) {
        let fileContent = await readEmbedFileContent(params, embed, currentParentFilePath);
        if (!fileContent) {
          continue;
        }
        fileContentArray.push(fileContent);
      } else if (isImg(embed.link)) {
        if (embed.link.startsWith("http")) {
          console.log("是网络图片");
          fileContentArray.push(embed.original);
        } else {
          console.log("是本地图片, 笔记文件路径 = " + normalizeFilePath);
          let imgPath = currentParentFilePath + "/" + embed.link;
          let normalizeImgPath = params.app.vault.adapter.path.posix.normalize(imgPath);
          normalizeImgPath = encodeURI(normalizeImgPath);
          let imgPathData = `![${embed.displayText}](${normalizeImgPath})`;
          fileContentArray.push(imgPathData);
        }
      } else {
        console.log("是其他数据, 不是图片, 也不是文本");
        fileContentArray.push(embed.original);
      }
    }
    let lastData = unsafeCachedData.substring(positionStartOffset, unsafeCachedData.length);
    fileContentArray.push(lastData);
    return fileContentArray.join("");
  }
}

function getEmbedPosition(embed) {
  let position = embed.position;
  let startOffset = position.start.offset;
  let endOffset = position.end.offset;
  return { startOffset, endOffset };
}
function getEmbedList(params, file) {
  let fileCache = params.app.metadataCache.getFileCache(file);
  return fileCache.embeds || [];
}
function getMdEmbedList(params, file) {
  let embeds = getEmbedList(params, file);
  let mdEmbeds = embeds.filter((embed) => {
    if (embed.link.endsWith(".md")) {
      return true;
    }
    return false;
  });
  return mdEmbeds;
}

module.exports = async (params) => {
  console.log("params.app.vault =");
  console.log(params.app.vault);
  const activeFile = params.app.workspace.getActiveFile();
  if (!activeFile) {
    new Notice("No active file.");
    return;
  }
  console.log("activeFile =");
  console.log(activeFile);

  let fileCache = await params.app.metadataCache.getFileCache(activeFile);
  console.log("fileCache =");
  console.log(fileCache);
  /* -------------------------------------------------------------------------- */
  let parentFilePath = activeFile.parent.path;
  let mdEmbeds = getMdEmbedList(params, activeFile);
  /* -------------------------------------------------------------------------- */
  // 读取文件内容
  // let fileContent = await params.app.vault.cachedRead(activeFile);
  let unsafeCachedData = activeFile.unsafeCachedData;
  let fileContentArray = [];
  let positionStartOffset = 0;
  var len = mdEmbeds.length;
  for (var i = 0; i < len; i++) {
    let embed = mdEmbeds[i];
    let position = getEmbedPosition(embed);

    let positionEndOffset = position.startOffset;

    let data = unsafeCachedData.substring(positionStartOffset, positionEndOffset);

    fileContentArray.push(data);
    positionStartOffset = position.endOffset;

    let fileContent = await readEmbedFileContent(params, embed, parentFilePath);
    if (!fileContent) {
      continue;
    }
    fileContentArray.push(fileContent);
  }

  let lastData = unsafeCachedData.substring(positionStartOffset, unsafeCachedData.length);
  fileContentArray.push(lastData);
  let data = fileContentArray.join("");
  /* -------------------------------------------------------------------------- */
  let myDate = new Date();
  let str = myDate.toTimeString(); //"10:55:24 GMT+0800 (中国标准时间)"
  let timeStr = str.substring(0, 8); //  '10:55:24'
  timeStr = "_" + timeStr.replace(/:/g, "_");
  /* -------------------------------------------------------------------------- */
  const path = `${parentFilePath}/${activeFile.basename + timeStr}.md`;
  if (data && !(await params.app.vault.adapter.exists(path))) {
    await params.app.vault.create(path, data);
    new Notice("Finished!");
    console.log("Finished!");
  } else {
    new Notice("No data to write.");
    console.log("No data to write.");
  }
};
